<?php
/**
 * Comment
 *
 * Класс Comment осуществляет обработку древовидных комментариев
 * @author Стребиж Артём <artyom1989@gmail.com>
 * @version 1.0
 */
class Comment extends Service_Pager{
	/**
	 * функция добавления комментария
	 *
	 * @param array $arrComment - 'text' - сам комментарий,
	 * 'idEssence' - id сущности (к примеру id конкретной статьи, с которой работает функция),
	 * 'type' - тип сущности (name)
	 * 'root' - параметр root - id того комментария, к которому выставлен этот, иначе - NULL
	 * @return boolean - результат добавления
	 */
	public function addComment($type, $root, $idEssence, $text, $idFirstRootComment = NULL, $idFolder = NULL) {
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		$e = Exception_Form::instance();
		$text = trim($text);
		if (empty($text))
			$e->addException('', 'Пустой комментарий');
		if ($e->isErrorExists())
			throw  $e;
		$objDB = Service_Database::instance();
		$essenceId = Service_Essence::getEssenceTypeID(($type));
		$time = Service_Date::gLocalTime2BD();
		if (!is_NULL($text)){
				$arrInsert = array
				('id_essence' => $idEssence,
				'essence_type' => $essenceId,
				'id_user' => $idUser,
				'text' => $text,
				'creation' => $time,
				'updated' => $time,
				'id_first_root_comment' => $idFirstRootComment
				);
		if ($root)
				$arrInsert['root_comment'] = $root;
			$result = $objDB->insertAutoincrement(DB_PREFIX.'comment', $arrInsert);
		}
		else
			$result = false;
		if (is_NULL($root) || $root == 0){
			if ($result)
				$objDB->update(DB_PREFIX.'comment', array('id_first_root_comment' => $result), array('id_comment' => $result));
		}
		else
		{
			if ($result)
				$objDB->update(DB_PREFIX.'comment', array('updated' => $time), array('id_comment' => $idFirstRootComment));
		}
		if ($result){
			// обновляем количество комментариев у сущности
			self::autoIncrementCommentAmount($idEssence, $type); // +
/*				if ($type == "tutorial_lesson"){
				$objTutorial = new Tutorial();
				$arrLesson = $objTutorial->getTutorialInfoFromIdLesson($idEssence);
				self::autoIncrementCommentAmount($arrLesson['id_article'], 'article');
			}*/
			//User_User::incrementEssenceInUserTable('comment', $idUser); // непонятно для чего
			Rating::addRating($result, 'comment', $idUser, 7, $idFolder); // +
			Statistics::addEvent(0, $idUser);//добавляем в статистику, 0 - добавление комментария // +
			
		}
		return $result;
	}

	/**
	 * функция делает выборку комментариев из БД и возвращает их в древовидной структуре
	 *
	 * @param int|string $type - тип сущности (в виде id или name Essence)
	 * @param int $idEssence - id сущности (к примеру id какой-то статьи)
	 * @param int $amount -
	 * @param int $order - тип сортировки 0- новые рутовые внизу, 1- новые рутовые сверху
	 * @return array - комментарии в древовидной структуре
	 */
	public function getComments($type, $idEssence, $amount = NULL, $order = 0){
		$objDB = Service_Database::instance();
		$essenceId = (int)Service_Essence::getEssenceTypeID($type);
		$essenceTypeName = Service_Essence::getEssenceTypeName($type);
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		$idUser = $idUser ? $idUser : 0;
		if (is_NULL($amount)){
			$stmt = 'SELECT `'.DB_PREFIX.'comment`.`text`, `'.DB_PREFIX.'users`.`first_name`, `'.DB_PREFIX.'users`.`last_name`, `users`.`id` as `id_user`, `'.DB_PREFIX.'comment`.`id_comment`,
					`'.DB_PREFIX.'comment`.`id_first_root_comment`,
					`'.DB_PREFIX.'comment`.`root_comment`, `'.DB_PREFIX.'comment`.`creation`, `'.DB_PREFIX.'comment`.`updated`, `'.DB_PREFIX.'comment`.`delete_flag`, `'.DB_PREFIX.'comment`.`who_edit`,
					`'.DB_PREFIX.'poll`.`mark` AS `session_user_poll`, `'.DB_PREFIX.'comment`.`marks_minus`, `'.DB_PREFIX.'comment`.`marks_plus`, `'.DB_PREFIX.'users`.`id_avatar`, `users`.`name`,
					`'.DB_PREFIX.'user_essence_last_impress_time`.`impress_time`
					FROM `'.DB_PREFIX.'comment`
					LEFT JOIN `users`
					ON `'.DB_PREFIX.'comment`.`id_user` = `users`.`id`
					LEFT JOIN `'.DB_PREFIX.'users` ON `'.DB_PREFIX.'users`.`id_user` = `'.DB_PREFIX.'comment`.`id_user` 
					LEFT JOIN `'.DB_PREFIX.'poll`
            		ON `'.DB_PREFIX.'poll`.`id_essence` = `'.DB_PREFIX.'comment`.`id_comment`
            		AND (`'.DB_PREFIX.'poll`.`essence_type` = 2)
								AND (`'.DB_PREFIX.'poll`.`id_user` = "' . $idUser . '")
					LEFT JOIN `'.DB_PREFIX.'user_essence_last_impress_time`
					ON `'.DB_PREFIX.'user_essence_last_impress_time`.`id_essence` = ' . $idEssence . '
					AND `'.DB_PREFIX.'user_essence_last_impress_time`.`essence_type` = ' . $essenceId  . '
					AND `'.DB_PREFIX.'user_essence_last_impress_time`.`id_user` = ' . $idUser . '
					WHERE `'.DB_PREFIX.'comment`.`id_essence` = ' . $idEssence . '
					AND `'.DB_PREFIX.'comment`.`essence_type` = ' . $essenceId;
					// . '
				//	ORDER BY `'.DB_PREFIX.'comment`.`updated` ' . $sort;
					$arrComments = $objDB->select($stmt);
					if (sizeof($arrComments) == 1 and $arrComments[0]['delete_flag']){
						unset($arrComments);
						$arrComments = array();
					}

					$arrCommentsIds = array();
					$size = sizeof($arrComments);
					for ($i=0; $i < $size; $i++){
/*						if ($arrComments[$i]['root_comment'] == NULL)
							$arrCommentsIds[$i] = 'minimizeCommentsBranch_' . $arrComments[$i]['id_comment'];*/
						if ($idUser != 0){
							if(is_NULL($arrComments[$i]['session_user_poll'])){
								if ($idUser == $arrComments[$i]['id_user'])
									$arrComments[$i]['session_user_poll'] = 0;
							}
						}
					}

					$allBranchHideFlag = User_Variable::getVariableValue($idUser, 'minimizeAllCommentsBranch');
		/*	$arrCommentsBranchMinimizeFlag = User_Variable::getVariableValue($idUser, $arrCommentsIds);
			$sizeArrBranchFlag = sizeof($arrCommentsBranchMinimizeFlag);
			echo '<pre>';
			print_r($arrCommentsBranchMinimizeFlag);
			echo '</pre>';*/
				if ($allBranchHideFlag == 1){
					for ($i=0; $i < $size; $i++){
						if ($arrComments[$i]['id_first_root_comment'] == $arrComments[$i]['id_comment'])
							$arrComments[$i]['minimizeCommentsBranch'] = 1;
					}
				}


/*			echo '<pre>';
			print_r($arrComments);
			echo '</pre>';*/
			/*$allBranchHideFlag = false;
			for ($i=0; $i < $sizeArrBranchFlag; $i++){
				if ($arrCommentsBranchMinimizeFlag[$i]['variable_value'] == 1)
					$allBranchHideFlag = true;
				else
					$allBranchHideFlag = false;
			}*/
				$sortField = 'creation';
				if ($type == 'community')
					$sortField = 'updated';
	    	$arrTreeComments = Service_ArrayConverter::sortTreeArray(Service_ArrayConverter::convertToTreeArray($arrComments, 'id_comment', 'root_comment'), $sortField, $order);
	    	if ($size > 0)
				$arrTreeComments[0]['minimizeAllCommentsBranch'] = $allBranchHideFlag;
/*					echo '<pre>';
			print_r($arrTreeComments);
			echo '</pre>';	*/
			if ($idUser)
				User_User::updateLastEssenceImpression($idEssence, $essenceId);
			return $arrTreeComments;
		}
		else
			return $this->getWall($idEssence, $type, $amount);
	}
	/**
	 * функция возвращает комментарий, если есть совпадения по трём параметрам
	 *
	 * @param int $idEssence - id сущности
	 * @param int|string $type - name сущности ( тип )
	 * @param int $idComment - id комментария
	 * @return array - массив со всеми параметрами комментария
	 */
	public static function getComment($idComment){
		$objDB = Service_Database::instance();
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		$idUser = $idUser ? $idUser : 0;
		$stmt = 'SELECT `'.DB_PREFIX.'comment`.`text`, `'.DB_PREFIX.'users`.`first_name`, `'.DB_PREFIX.'users`.`last_name`, `users`.`id` as `id_user`, `'.DB_PREFIX.'comment`.`id_comment`,
					`'.DB_PREFIX.'comment`.`id_first_root_comment`, `'.DB_PREFIX.'comment`.`id_essence`, `'.DB_PREFIX.'comment`.`essence_type`,
					`'.DB_PREFIX.'comment`.`root_comment`, `'.DB_PREFIX.'comment`.`creation`, `'.DB_PREFIX.'comment`.`updated`, `'.DB_PREFIX.'comment`.`delete_flag`, `'.DB_PREFIX.'comment`.`who_edit`,
					`'.DB_PREFIX.'poll`.`mark` AS `session_user_poll`, `'.DB_PREFIX.'comment`.`marks_minus`, `'.DB_PREFIX.'comment`.`marks_plus`, `'.DB_PREFIX.'users`.`id_avatar`, `users`.`name`,
					`'.DB_PREFIX.'users`.`rating`, `'.DB_PREFIX.'user_essence_last_impress_time`.`impress_time`
					FROM `'.DB_PREFIX.'comment`
					LEFT JOIN `users`
					ON `'.DB_PREFIX.'comment`.`id_user` = `users`.`id`
					LEFT JOIN `'.DB_PREFIX.'users` ON `'.DB_PREFIX.'users`.`id_user` = `'.DB_PREFIX.'comment`.`id_user`
					LEFT JOIN `'.DB_PREFIX.'poll`
            		ON `'.DB_PREFIX.'poll`.`id_essence` = `'.DB_PREFIX.'comment`.`id_comment`
            		AND (`'.DB_PREFIX.'poll`.`essence_type` = 2)
					AND (`'.DB_PREFIX.'poll`.`id_user` = "' . $idUser . '")
					LEFT JOIN `'.DB_PREFIX.'user_essence_last_impress_time`
					ON `'.DB_PREFIX.'user_essence_last_impress_time`.`id_essence` = `'.DB_PREFIX.'comment`.`id_essence`
					AND `'.DB_PREFIX.'user_essence_last_impress_time`.`essence_type` = `'.DB_PREFIX.'comment`.`essence_type`
					AND `'.DB_PREFIX.'user_essence_last_impress_time`.`id_user` = ' . $idUser . '
					WHERE `'.DB_PREFIX.'comment`.`id_comment` = ' . $idComment;
		$arrTemp = $objDB->select($stmt);
		if (sizeof($arrTemp) > 0 && $idUser != 0){
			if(is_NULL($arrTemp[0]['session_user_poll'])){
				if ($idUser == $arrTemp[0]['id_user'])
					$arrTemp[0]['session_user_poll'] = 0;
							}
						}
		return $arrTemp;
	}

	public function getCommentsCollectionByIDs($arrEssencesIDs, $type, $idComment){
		$objDB = Service_Database::instance();
		$essenceId = Service_Essence::getEssenceTypeID($type);
		$stmt = 'SELECT `'.DB_PREFIX.'comment`.`text`, `'.DB_PREFIX.'users`.`first_name`, `'.DB_PREFIX.'users`.`last_name`, `users`.`id` as `id_user`, `'.DB_PREFIX.'comment`.`id_comment`,
		`'.DB_PREFIX.'comment`.`id_first_root_comment`,
		`'.DB_PREFIX.'comment`.`root_comment`, `'.DB_PREFIX.'comment`.`creation`, `'.DB_PREFIX.'comment`.`updated`, `'.DB_PREFIX.'comment`.`delete_flag`, `'.DB_PREFIX.'comment`.`who_edit`, `'.DB_PREFIX.'users`.`rating`
		FROM `'.DB_PREFIX.'comment`
		LEFT JOIN `users`
		ON `'.DB_PREFIX.'comment`.`id_user` = `users`.`id`
		LEFT JOIN `'.DB_PREFIX.'users` ON `'.DB_PREFIX.'users`.`id_user` = `'.DB_PREFIX.'comment`.`id_user`
		WHERE `'.DB_PREFIX.'comment`.`id_essence` = ' . $idEssence .
		' AND `'.DB_PREFIX.'comment`.`essence_type` = ' . $essenceId .
		' AND `'.DB_PREFIX.'comment`.`id_comment` IN(' . join(',', $arrEssencesIDs) . ')';
		return $objDB->select($stmt);
	}

	/**
	 * функция определения id комментария
	 *
	 * @param string $comment - текст комментария
	 * @param int $idEssence - id сущности
	 * @param int|string $type - name сущности ( тип )
	 * @param int $root - параметр root_comment комментария
	 * @return int - id комментария, если есть совпадения
	 */
	public function getCommentId($comment, $idEssence, $type, $root){
		$objDB = Service_Database::instance();
		if (is_NULL($root))
			$rootWhere = '';
		else
			$rootWhere = ' AND `'.DB_PREFIX.'comment`.`root_comment` = ' . $root;
		$essenceId = Service_Essence::getEssenceTypeID($type);
		$stmt = 'SELECT `'.DB_PREFIX.'comment`.`id_comment`
				FROM `'.DB_PREFIX.'comment`
				WHERE `'.DB_PREFIX.'comment`.`id_essence` = "' . $idEssence .
				'" AND `'.DB_PREFIX.'comment`.`essence_type` = "' . $essenceId .
		$rootWhere .
				'" AND `'.DB_PREFIX.'comment`.`text` = "' . $comment . '"';
		return $objDB->selectSimpleField($stmt);
	}

	public function getWall($idEssence, $essenceType, $pageNum = 1){
		$objDB = Service_Database::instance();
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		$idUser = $idUser ? $idUser : 0;
		$stmtWhere = "WHERE `id_essence` = '" . $idEssence . "' AND `essence_type` = '" . $essenceType . "' AND `root_comment` IS NULL";
		$stmt = "
		SELECT COUNT(`".DB_PREFIX."comment`.`id_comment`) AS `comment_count`
		FROM `".DB_PREFIX."comment`"
		 . $stmtWhere;
		$this->setItemCount($objDB->selectSimpleField($stmt));

		$stmt = "
		SELECT `".DB_PREFIX."comment`.`id_comment`, `".DB_PREFIX."comment`.`updated`
		FROM `".DB_PREFIX."comment`
		" . $stmtWhere . "
		ORDER BY `updated` DESC
		" . $this->makeLimits($pageNum);
		$arrFirstRootComment = $objDB->select($stmt);
		$sizeArrFirstRootComment = sizeof($arrFirstRootComment);

		if ($sizeArrFirstRootComment > 0){//формирование запроса для всех коментариев стены
			for ($num = 1, $stmtWhere = "WHERE `id_first_root_comment` = '" . $arrFirstRootComment[0]['id_comment'] . "'"; $num < $sizeArrFirstRootComment; $num++){
				$stmtWhere = $stmtWhere . " OR `id_first_root_comment` = '" . $arrFirstRootComment[$num]['id_comment'] . "'";
			}
			$stmt = "
			SELECT `".DB_PREFIX."comment`.`text`, `".DB_PREFIX."users`.`first_name`, `".DB_PREFIX."users`.`last_name`, `users`.`id` as `id_user`, `users`.`name`, `".DB_PREFIX."comment`.`id_comment`,
			`".DB_PREFIX."comment`.`id_first_root_comment`,
			`".DB_PREFIX."comment`.`root_comment`, `".DB_PREFIX."comment`.`creation`, `".DB_PREFIX."comment`.`updated`, `".DB_PREFIX."comment`.`delete_flag`, `".DB_PREFIX."comment`.`who_edit`,
			`".DB_PREFIX."poll`.`mark` AS `session_user_".DB_PREFIX."poll`, `".DB_PREFIX."comment`.`marks_minus`, `".DB_PREFIX."comment`.`marks_plus`, `".DB_PREFIX."users`.`id_avatar`, `users`.`name`,
			`".DB_PREFIX."user_essence_last_impress_time`.`impress_time`
			FROM `".DB_PREFIX."comment`
			LEFT JOIN `users`
			ON `".DB_PREFIX."comment`.`id_user` = `users`.`id`
			LEFT JOIN `".DB_PREFIX."users` ON `".DB_PREFIX."users`.`id_user` = `".DB_PREFIX."comment`.`id_user`
			LEFT JOIN `".DB_PREFIX."poll`
            ON `".DB_PREFIX."poll`.`id_essence` = `".DB_PREFIX."comment`.`id_comment`
            AND (`".DB_PREFIX."poll`.`essence_type` = 2)
			AND (`".DB_PREFIX."poll`.`id_user` = '" . $idUser . "')
			LEFT JOIN `".DB_PREFIX."user_essence_last_impress_time`
			ON `".DB_PREFIX."user_essence_last_impress_time`.`id_essence` = `".DB_PREFIX."comment`.`id_essence`
			AND `".DB_PREFIX."user_essence_last_impress_time`.`essence_type` = `".DB_PREFIX."comment`.`essence_type`
			AND `".DB_PREFIX."user_essence_last_impress_time`.`id_user` = " . $idUser . " "
			. $stmtWhere;
			$arrComments = $objDB->select($stmt);
			$arrCommentsIds = array();
			$size = sizeof($arrComments);
			for ($i=0; $i < $size; $i++){
				if ($idUser != 0){
					if(is_NULL($arrComments[$i]['session_user_poll'])){
						if ($idUser == $arrComments[$i]['id_user'])
							$arrComments[$i]['session_user_poll'] = 0;
					}
				}
			}
			$allBranchHideFlag = User_Variable::getVariableValue($idUser, 'minimizeAllCommentsBranch');
//			$arrCommentsBranchMinimizeFlag = User_Variable::getVariableValue($idUser, $arrCommentsIds);
//			$sizeArrBranchFlag = sizeof($arrCommentsBranchMinimizeFlag);
/*			echo '<pre>';
			print_r($arrCommentsBranchMinimizeFlag);
			echo '</pre>';*/
			if ($allBranchHideFlag == 1){
				for ($i=0; $i < $size; $i++){
					if ($arrComments[$i]['id_first_root_comment'] == $arrComments[$i]['id_comment'])
						$arrComments[$i]['minimizeCommentsBranch'] = 1;
				}
			}
			$arrComment = Service_ArrayConverter::sortTreeArray(Service_ArrayConverter::convertToTreeArray($arrComments, 'id_comment', 'root_comment'), 'updated', 1);
	    if ($size > 0)
				$arrComment[0]['minimizeAllCommentsBranch'] = $allBranchHideFlag;
		}
		else $arrComment = NULL;
		return $arrComment;
	}

	/**
	 * получаем комменатрии пользователя
	 */
	public function getUsersComments($login, $pageNum){
		$objDB = Service_Database::instance();
		$stmtWhere = " WHERE `users`.`name` = '" . $login . "' AND `".DB_PREFIX."comment`.`delete_flag` = 0";

		$arrEssence = Service_Essence::getEssenceTypeNameForUserComment();
		foreach ($arrEssence as $essenceName) {
			$essenceIdField = Service_Essence::getEssenceIdFieldNameByName($essenceName);
			$stmt = 'SELECT `'.DB_PREFIX.$essenceName.'`.`'.$essenceIdField.'`, `essence_author`.`id_avatar` as `id_avatar`,
			`essence_author`.`id_user` as `id_author`';
			if ($essenceName == 'community') $stmt .= ' `folder`.`name` as `essence_name`,';
			elseif ($essenceName == 'feed_back') $stmt .= ' `'.DB_PREFIX.$essenceName.'`.`text` as `essence_name`,';
			else $stmt .= ' `'.DB_PREFIX.$essenceName.'`.`name` as `essence_name`,';

			$stmt .=' `'.DB_PREFIX.'comment`.`text`,
					 `'.DB_PREFIX.'users`.`first_name`,
					 `'.DB_PREFIX.'users`.`last_name`,
					 `users`.`id` as `id_user`,
					 `users`.`name`,
					 `'.DB_PREFIX.'comment`.`id_comment`,
					 `'.DB_PREFIX.'comment`.`essence_type`,
					 `'.DB_PREFIX.'comment`.`id_essence`,
					 `'.DB_PREFIX.'comment`.`id_first_root_comment`,
			`'.DB_PREFIX.'comment`.`root_comment`, `'.DB_PREFIX.'comment`.`creation`, `'.DB_PREFIX.'comment`.`updated`, `'.DB_PREFIX.'comment`.`delete_flag`, `'.DB_PREFIX.'comment`.`who_edit`,
			`'.DB_PREFIX.'poll`.`mark` AS `session_user_poll`, `'.DB_PREFIX.'comment`.`marks_minus`, `'.DB_PREFIX.'comment`.`marks_plus`, `users`.`name`
			FROM `'.DB_PREFIX.'comment`
			LEFT JOIN `users` ON `'.DB_PREFIX.'comment`.`id_user` = `users`.`id`
			LEFT JOIN `'.DB_PREFIX.'users` ON `'.DB_PREFIX.'users`.`id_user` = `'.DB_PREFIX.'comment`.`id_user`
			LEFT JOIN `'.DB_PREFIX.'poll` ON `'.DB_PREFIX.'poll`.`id_essence` = `'.DB_PREFIX.'comment`.`id_comment` AND
													`'.DB_PREFIX.'poll`.`essence_type` = `'.DB_PREFIX.'comment`.`essence_type` AND
													`'.DB_PREFIX.'poll`.`id_user` = `users`.`id`
			LEFT JOIN `'.DB_PREFIX.$essenceName.'` ON `'.DB_PREFIX.$essenceName.'`.`'.$essenceIdField.'` = `'.DB_PREFIX.'comment`.`id_essence`
			LEFT JOIN `'.DB_PREFIX.'users` as `essence_author` ON `essence_author`.`id_user` = `'.DB_PREFIX.$essenceName.'`.`id_user` ';

/*			$stmt .= 'LEFT JOIN `folder` ON `folder`.`id_folder` = ';
			if ($essenceName == 'community') $stmt .= ' `community`.`id_community`';
			elseif ($essenceName == 'feed_back') $stmt .= ' `feed_back`.`id_feed_back`';
			elseif ($essenceName == 'article') $stmt .= ' `article`.`id_essence`';
			elseif ($essenceName == 'tutorial_lesson') $stmt .= ' `tutorial`.`id_folder`';
			else $stmt .= ' `'.DB_PREFIX.$essenceName.'`.`id_folder`';*/


			$stmt	.= $stmtWhere . ' AND `'.DB_PREFIX.'comment`.`essence_type` = ' . Service_Essence::getEssenceTypeIDByName($essenceName) . '
	    ORDER BY `'.DB_PREFIX.'comment`.`creation` DESC;';
			//echo $stmt;
			$arrComments[] = $objDB->select($stmt);

		}
		$arrResult = Service_ArrayConverter::mergeAndSortArrays($arrComments, 'creation', 1);

		$size = sizeof($arrResult);
		$this->setItemCount($size);
		if ($pageNum > 0) {//Если задан номер страницы
			$begin = ($pageNum - 1) * $this->getItemsPerPage();
			$end = $size < ($begin + $this->getItemsPerPage()) ? $size : ($begin + $this->getItemsPerPage());
    }else {$begin = 0; $end = $this->getItemsPerPage();}
    unset($arrComments);
    $arrComments = array();
    for ($i=$begin;$i<$end;$i++)
    	$arrComments[] = $arrResult[$i];

    return $arrComments;


/*		$stmt = "
		SELECT `".DB_PREFIX."comment`.`text`,
					 `".DB_PREFIX."users`.`first_name`,
					 `".DB_PREFIX."users`.`last_name`,
					 `users`.`id` as `id_user`,
					 `users`.`name`,
					 `".DB_PREFIX."comment`.`id_comment`,
					 `".DB_PREFIX."comment`.`essence_type`,
					 `".DB_PREFIX."comment`.`id_essence`,
		`".DB_PREFIX."comment`.`id_first_root_comment`,
		`".DB_PREFIX."comment`.`root_comment`, `".DB_PREFIX."comment`.`creation`, `".DB_PREFIX."comment`.`updated`, `".DB_PREFIX."comment`.`delete_flag`, `".DB_PREFIX."comment`.`who_edit`,
		`poll`.`mark` AS `session_user_poll`, `".DB_PREFIX."comment`.`marks_minus`, `".DB_PREFIX."comment`.`marks_plus`, `".DB_PREFIX."users`.`id_avatar`, `users`.`name`
		FROM `".DB_PREFIX."comment`
		LEFT JOIN `users` ON `".DB_PREFIX."comment`.`id_user` = `users`.`id`
		LEFT JOIN `poll` ON `poll`.`id_essence` = `".DB_PREFIX."comment`.`id_comment` AND
												`poll`.`essence_type` = `".DB_PREFIX."comment`.`essence_type` AND
												`poll`.`id_user` = `users`.`name`" . $stmtWhere . "
    ORDER BY `".DB_PREFIX."comment`.`creation` DESC
    " . $this->makeLimits($pageNum);

		return $objDB->select($stmt);*/
	}

	/**
	 * функция возвращает количество коментариев у сущиности
	 *
	 * @param unknown_type $idEssence
	 * @param unknown_type $essenceType
	 * @return unknown
	 */
	public static function getCountOfComment($idEssence, $essenceType){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT COUNT(`".DB_PREFIX."comment`.`id_comment`) AS `comment_count`
		FROM `".DB_PREFIX."comment`
		WHERE `id_essence` = '" . $idEssence . "' AND `essence_type` = '" . $essenceType . "'";
		return $root = $objDB->selectSimpleField($stmt);
	}

	public static function editComment($idComment, $newComment, $status = 'edit', $idAuthor = NULL){
		$objDB = Service_Database::instance();
		$time = Service_Date::gLocalTime2BD();
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		
		if (User_User::staticCheckIfUser("admin", $idUser)) $whoEdit = 2;
		elseif ($idAuthor) $whoEdit = $idAuthor;
		$arrUpdate = array(
		'text' => $newComment,
		'updated' => $time,
		'who_edit' => $whoEdit, // id_user - то редактировал автор, если 2 - то админ
		);
		if ($status == 'delete'){
			$arrUpdate['delete_flag'] = 1; // коммент удалён
			self::autoDecrementCommentAmountForUser($idAuthor);
		}
		$objDB->update(DB_PREFIX.'comment', $arrUpdate, array('id_comment' => $idComment));
	}

	public static function autoIncrementCommentAmount($idEssence, $essenceType){
		$objDB = Service_Database::instance();
		$essenceId = Service_Essence::getEssenceTypeID($essenceType);
		$essenceName = Service_Essence::getEssenceTypeName($essenceId);
		$essenceIdField = Service_Essence::getEssenceIdFieldNameById($essenceId);
		$stmt = "UPDATE `" . DB_PREFIX.$essenceName . "`
	             SET `comment_amount`=(`comment_amount`+1)
	             WHERE `" . $essenceIdField . "`='" . $idEssence . "'";
	  	$objDB->query($stmt);
	}

	public static function autoDecrementCommentAmount($idEssence, $essenceType){
		$objDB = Service_Database::instance();
		$essenceId = Service_Essence::getEssenceTypeID($essenceType);
		$essenceName = Service_Essence::getEssenceTypeName($essenceId);
		$essenceIdField = Service_Essence::getEssenceIdFieldNameById($essenceId);
		$stmt = "UPDATE `" . DB_PREFIX.$essenceName . "`
	             SET `comment_amount`=(`comment_amount`-1)
	             WHERE `" . $essenceIdField . "`='" . $idEssence . "'";
	  	$objDB->query($stmt);
	}

	/**
	 * Уменьшает количество комментариев пользователя
	 * работает с таблицей DB_PREFIX."contact_user_settings"
	 *
	 * @param int $idUser
	 */
	public static function autoDecrementCommentAmountForUser($idUser){
		$objDB = Service_Database::instance();
		$stmt = "UPDATE `".DB_PREFIX."users`
	             SET `".DB_PREFIX."users`.`comment_amount`=(`".DB_PREFIX."users`.`comment_amount`-1)
	             WHERE `".DB_PREFIX."users`.`id_user`='" . $idUser . "'";
	  	$objDB->query($stmt);
	}

	public static function autoIncrementCommentAmountForUser($idUser){
		$objDB = Service_Database::instance();
		$stmt = "UPDATE `".DB_PREFIX."users`
	             SET `".DB_PREFIX."users`.`comment_amount`=(`".DB_PREFIX."users`.`comment_amount`+1)
	             WHERE `".DB_PREFIX."users`.`id_user`='" . $idUser . "'";
	  	$objDB->query($stmt);
	}

	/**
	 * функция делает выборку новых комментариев из БД
	 *
	 * @param int|string $type - тип сущности (в виде id или name Essence)
	 * @param int $idEssence - id сущности (к примеру id какой-то статьи)
	 * @param int $amount -
	 * @param int $order - тип сортировки 0- новые рутовые внизу, 1- новые рутовые сверху
	 * @return array - комментарии в древовидной структуре
	 */
	public function getNewComments($type, $idEssence, $amount = NULL, $order = 0){
		$objDB = Service_Database::instance();
		$essenceId = Service_Essence::getEssenceTypeID($type);
		$objSession = User_Session::instance();
		$idUser = $objSession->getUserId();
		$idUser = $idUser ? $idUser : 0;
		if (is_NULL($amount)){
			$stmt = ' SELECT `'.DB_PREFIX.'comment`.`text`, `'.DB_PREFIX.'users`.`first_name`, `'.DB_PREFIX.'users`.`last_name`, `users`.`id` as `id_user`, `'.DB_PREFIX.'comment`.`id_comment`,
								`'.DB_PREFIX.'comment`.`id_first_root_comment`,
								`'.DB_PREFIX.'comment`.`root_comment`, `'.DB_PREFIX.'comment`.`creation`, `'.DB_PREFIX.'comment`.`updated`, `'.DB_PREFIX.'comment`.`delete_flag`, `'.DB_PREFIX.'comment`.`who_edit`,
								`'.DB_PREFIX.'poll`.`mark` AS `session_user_poll`, `'.DB_PREFIX.'comment`.`marks_minus`, `'.DB_PREFIX.'comment`.`marks_plus`, `'.DB_PREFIX.'users`.`id_avatar`, `users`.`name`,
								`'.DB_PREFIX.'user_essence_last_impress_time`.`impress_time`
								FROM `'.DB_PREFIX.'comment`
								LEFT JOIN `users`
								ON `'.DB_PREFIX.'comment`.`id_user` = `users`.`id`
								LEFT JOIN `'.DB_PREFIX.'poll`
            		ON `'.DB_PREFIX.'poll`.`id_essence` = `'.DB_PREFIX.'comment`.`id_comment`
            		AND (`'.DB_PREFIX.'poll`.`essence_type` = 2)
								AND (`'.DB_PREFIX.'poll`.`id_user` = "' . $idUser . '")
								LEFT JOIN `'.DB_PREFIX.'user_essence_last_impress_time`
								ON `'.DB_PREFIX.'user_essence_last_impress_time`.`id_essence` = ' . $idEssence . '
								AND `'.DB_PREFIX.'user_essence_last_impress_time`.`essence_type` = ' . $essenceId  . '
								AND `'.DB_PREFIX.'user_essence_last_impress_time`.`id_user` = ' . $idUser . '
								WHERE `'.DB_PREFIX.'comment`.`id_essence` = ' . $idEssence . '
								AND `'.DB_PREFIX.'comment`.`creation` >= `'.DB_PREFIX.'user_essence_last_impress_time`.`impress_time`
								AND `'.DB_PREFIX.'comment`.`id_user` != ' . $idUser . '
								AND `'.DB_PREFIX.'comment`.`essence_type` = ' . $essenceId;
					$arrComments = $objDB->select($stmt);
					if (sizeof($arrComments) == 1 and $arrComments[0]['delete_flag']){
						unset($arrComments);
						$arrComments = array();
					}
					$arrCommentsIds = array();
					$size = sizeof($arrComments);
					for ($i=0; $i < $size; $i++){
						if ($idUser != 0){
							if(is_NULL($arrComments[$i]['session_user_poll'])){
								if ($idUser == $arrComments[$i]['id_user'])
									$arrComments[$i]['session_user_poll'] = 0;
							}
						}
					}
					$allBranchHideFlag = User_Variable::getVariableValue($idUser, 'minimizeAllCommentsBranch');
					if ($allBranchHideFlag == 1){
						for ($i=0; $i < $size; $i++){
							if ($arrComments[$i]['id_first_root_comment'] == $arrComments[$i]['id_comment'])
								$arrComments[$i]['minimizeCommentsBranch'] = 1;
						}
					}
//					print_r($arrComments);
					$sortField = 'creation';
					if ($type == 'community')
						$sortField = 'updated';
					$arrTreeComments = Service_ArrayConverter::convertToTreeArray($arrComments, 'id_comment', 'root_comment');
					for ($i=0; $i < $size; $i++){
						$isset = true;
						if ($arrComments[$i]['root_comment'] != null){
							for ($j=0; $j<$size;$j++){
								$isset = false;
								if ($arrComments[$j]['id_comment'] == $arrComments[$i]['root_comment']){
									$isset = true;
									break;
								}
							}
							if (!$isset)
								$arrTreeComments[] = $arrComments[$i];
						}
					}
		    	$arrTreeComments = Service_ArrayConverter::sortTreeArray($arrTreeComments, $sortField, $order);

		    	if ($size > 0)
						$arrTreeComments[0]['minimizeAllCommentsBranch'] = $allBranchHideFlag;
//					print_r($arrTreeComments);
					// сохранять время просмотра
					if ($idUser)
						User_User::updateLastEssenceImpression($idEssence, $essenceId);
					return $arrTreeComments;
		}
		else
			return $this->getNewWall($idEssence, $type, $amount);
	}
	/**
	 * Удаление комментариев у удаленной сущности
	 *
	 * @param string $essenceType
	 * @param int $idEssence
	 */
	public static function deleteCommentsByDeletedEssence($essenceType, $idEssence){
		$essenceTypeID = (int)Service_Essence::getEssenceTypeID($essenceType);
		$essenceTypeName = Service_Essence::getEssenceTypeName($essenceType);
		self::_deleteComments(self::_getCommentIds($essenceTypeID, $idEssence));
	}

	private static function _deleteComments($arrIds){
		$objDB = Service_Database::instance();
		if (sizeof($arrIds) > 0)
			foreach ($arrIds as $idComment)
				$objDB->delete(DB_PREFIX.'comment', array('id_comment' => $idComment));
	}

	private static function _getCommentIds($essenceType, $idEssence){
		$objDB = Service_Database::instance();
		$sql = "SELECT `".DB_PREFIX."comment`.`id_comment`
						FROM comment
						WHERE `".DB_PREFIX."comment`.`essence_type` = " . $essenceType . "
						AND `".DB_PREFIX."comment`.`id_essence` = " . $idEssence;
		return $objDB->selectSimpleArray($sql);
	}
}
?>